<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>热词统计 - 舆情分析系统</title>
    <link rel="stylesheet" href="../../lib/layui/css/layui.css">
    <link rel="stylesheet" href="../../css/common.css">
    <style>
        .container {
            padding: 20px;
            background: #f5f5f5;
            min-height: 100vh;
        }
        
        .page-header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .page-title {
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin: 0;
        }
        
        .filter-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .chart-container {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .chart-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 20px;
        }
        
        .chart-wrapper {
            height: 400px;
        }
        
        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .stat-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .stat-number {
            font-size: 28px;
            font-weight: bold;
            color: #1890ff;
            margin-bottom: 10px;
        }
        
        .stat-label {
            color: #666;
            font-size: 14px;
        }
        
        .table-container {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .loading {
            text-align: center;
            padding: 50px;
            color: #999;
        }
    </style>
</head>
<body>
    <div id="app" class="container">
        <!-- 页面头部 -->
        <div class="page-header">
            <h1 class="page-title">热词统计</h1>
        </div>

        <!-- 筛选条件 -->
        <div class="filter-section">
            <form class="layui-form" lay-filter="filterForm">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">统计日期</label>
                        <div class="layui-input-inline">
                            <input type="text" class="layui-input" id="dateRange" placeholder="请选择日期范围">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">分类</label>
                        <div class="layui-input-inline">
                            <select name="category" lay-filter="category">
                                <option value="">全部分类</option>
                                <option value="科技">科技</option>
                                <option value="汽车">汽车</option>
                                <option value="教育">教育</option>
                                <option value="医疗">医疗</option>
                                <option value="社会">社会</option>
                                <option value="经济">经济</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button type="button" class="layui-btn" @click="searchData">查询</button>
                        <button type="button" class="layui-btn layui-btn-primary" @click="resetFilter">重置</button>
                    </div>
                </div>
            </form>
        </div>

        <!-- 统计卡片 -->
        <div class="stats-cards">
            <div class="stat-card">
                <div class="stat-number">{{ stats.totalWords }}</div>
                <div class="stat-label">总热词数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">{{ stats.totalFrequency }}</div>
                <div class="stat-label">总频次</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">{{ stats.avgSentiment }}</div>
                <div class="stat-label">平均情感得分</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">{{ stats.topCategory }}</div>
                <div class="stat-label">热门分类</div>
            </div>
        </div>

        <!-- 热词排行榜 -->
        <div class="chart-container">
            <h3 class="chart-title">热词排行榜</h3>
            <div id="hotWordChart" class="chart-wrapper"></div>
        </div>

        <!-- 热词情感分布 -->
        <div class="chart-container">
            <h3 class="chart-title">热词情感分布</h3>
            <div id="sentimentChart" class="chart-wrapper"></div>
        </div>

        <!-- 分类热词统计 -->
        <div class="chart-container">
            <h3 class="chart-title">分类热词统计</h3>
            <div id="categoryChart" class="chart-wrapper"></div>
        </div>

        <!-- 热词趋势 -->
        <div class="chart-container">
            <h3 class="chart-title">热词趋势分析</h3>
            <div id="trendChart" class="chart-wrapper"></div>
        </div>

        <!-- 热词详情表格 -->
        <div class="table-container">
            <h3 class="chart-title">热词详情</h3>
            <table id="hotWordTable" lay-filter="hotWordTable"></table>
        </div>
    </div>

    <!-- 引入依赖 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="../../lib/echarts/echarts.min.js"></script>
    <script src="../../lib/layui/layui.js"></script>
    <script src="../../js/api.js"></script>
    
    <script>
        new Vue({
            el: '#app',
            data: {
                stats: {
                    totalWords: 0,
                    totalFrequency: 0,
                    avgSentiment: 0,
                    topCategory: ''
                },
                hotWordChart: null,
                sentimentChart: null,
                categoryChart: null,
                trendChart: null,
                filterParams: {
                    startDate: '',
                    endDate: '',
                    category: ''
                },
                loading: false
            },
            mounted() {
                this.initLayui();
                this.initCharts();
                this.loadData();
            },
            methods: {
                // 初始化Layui
                initLayui() {
                    layui.use(['form', 'table', 'laydate'], () => {
                        const form = layui.form;
                        const table = layui.table;
                        const laydate = layui.laydate;
                        
                        // 初始化日期选择器
                        laydate.render({
                            elem: '#dateRange',
                            type: 'date',
                            range: true,
                            done: (value) => {
                                if (value) {
                                    const dates = value.split(' - ');
                                    this.filterParams.startDate = dates[0];
                                    this.filterParams.endDate = dates[1];
                                }
                            }
                        });
                        
                        // 初始化表格
                        table.render({
                            elem: '#hotWordTable',
                            url: '/api/opinion/hot-words',
                            method: 'get',
                            where: this.filterParams,
                            cols: [[
                                {field: 'word', title: '热词', width: 150},
                                {field: 'frequency', title: '频次', width: 100, sort: true},
                                {field: 'category', title: '分类', width: 100},
                                {field: 'sentiment_score', title: '情感得分', width: 120},
                                {field: 'positive_count', title: '正面次数', width: 120},
                                {field: 'negative_count', title: '负面次数', width: 120},
                                {field: 'neutral_count', title: '中性次数', width: 120},
                                {field: 'stat_date', title: '统计日期', width: 120}
                            ]],
                            page: true,
                            limit: 20,
                            limits: [10, 20, 50, 100]
                        });
                        
                        form.render();
                    });
                },

                // 初始化图表
                initCharts() {
                    // 热词排行榜图表
                    this.hotWordChart = echarts.init(document.getElementById('hotWordChart'));
                    
                    // 情感分布图表
                    this.sentimentChart = echarts.init(document.getElementById('sentimentChart'));
                    
                    // 分类统计图表
                    this.categoryChart = echarts.init(document.getElementById('categoryChart'));
                    
                    // 趋势分析图表
                    this.trendChart = echarts.init(document.getElementById('trendChart'));
                },

                // 加载数据
                async loadData() {
                    try {
                        this.loading = true;
                        
                        // 加载统计数据
                        await this.loadStats();
                        
                        // 加载图表数据
                        await this.loadChartData();
                        
                    } catch (error) {
                        console.error('加载数据失败:', error);
                        layui.use('layer', () => {
                            layui.layer.msg('加载数据失败', {icon: 2});
                        });
                    } finally {
                        this.loading = false;
                    }
                },

                // 加载统计数据
                async loadStats() {
                    try {
                        const response = await API.opinion.getHotWordsStats(this.filterParams);
                        this.stats = response;
                    } catch (error) {
                        console.error('加载统计数据失败:', error);
                        // 使用模拟数据
                        this.stats = {
                            totalWords: 156,
                            totalFrequency: 2840,
                            avgSentiment: 0.35,
                            topCategory: '科技'
                        };
                    }
                },

                // 加载图表数据
                async loadChartData() {
                    try {
                        const response = await API.opinion.getHotWords(this.filterParams);
                        this.updateCharts(response);
                    } catch (error) {
                        console.error('加载图表数据失败:', error);
                        // 使用模拟数据
                        this.updateCharts(this.getMockData());
                    }
                },

                // 更新图表
                updateCharts(data) {
                    this.updateHotWordChart(data);
                    this.updateSentimentChart(data);
                    this.updateCategoryChart(data);
                    this.updateTrendChart(data);
                },

                // 更新热词排行榜
                updateHotWordChart(data) {
                    const option = {
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'value'
                        },
                        yAxis: {
                            type: 'category',
                            data: data.slice(0, 10).map(item => item.word)
                        },
                        series: [
                            {
                                name: '频次',
                                type: 'bar',
                                data: data.slice(0, 10).map(item => ({
                                    value: item.frequency,
                                    itemStyle: {
                                        color: item.sentiment_score > 0 ? '#52c41a' : 
                                               item.sentiment_score < 0 ? '#ff4d4f' : '#faad14'
                                    }
                                }))
                            }
                        ]
                    };
                    this.hotWordChart.setOption(option);
                },

                // 更新情感分布图表
                updateSentimentChart(data) {
                    const positive = data.filter(item => item.sentiment_score > 0).length;
                    const negative = data.filter(item => item.sentiment_score < 0).length;
                    const neutral = data.filter(item => item.sentiment_score === 0).length;
                    
                    const option = {
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b}: {c} ({d}%)'
                        },
                        legend: {
                            orient: 'vertical',
                            left: 'left'
                        },
                        series: [
                            {
                                name: '情感分布',
                                type: 'pie',
                                radius: ['40%', '70%'],
                                avoidLabelOverlap: false,
                                label: {
                                    show: false,
                                    position: 'center'
                                },
                                emphasis: {
                                    label: {
                                        show: true,
                                        fontSize: '18',
                                        fontWeight: 'bold'
                                    }
                                },
                                labelLine: {
                                    show: false
                                },
                                data: [
                                    { value: positive, name: '正面', itemStyle: { color: '#52c41a' } },
                                    { value: neutral, name: '中性', itemStyle: { color: '#faad14' } },
                                    { value: negative, name: '负面', itemStyle: { color: '#ff4d4f' } }
                                ]
                            }
                        ]
                    };
                    this.sentimentChart.setOption(option);
                },

                // 更新分类统计图表
                updateCategoryChart(data) {
                    const categoryMap = {};
                    data.forEach(item => {
                        if (categoryMap[item.category]) {
                            categoryMap[item.category] += item.frequency;
                        } else {
                            categoryMap[item.category] = item.frequency;
                        }
                    });
                    
                    const categories = Object.keys(categoryMap);
                    const frequencies = Object.values(categoryMap);
                    
                    const option = {
                        tooltip: {
                            trigger: 'item'
                        },
                        series: [
                            {
                                name: '分类统计',
                                type: 'pie',
                                radius: '50%',
                                data: categories.map((category, index) => ({
                                    value: frequencies[index],
                                    name: category
                                })),
                                emphasis: {
                                    itemStyle: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]
                    };
                    this.categoryChart.setOption(option);
                },

                // 更新趋势分析图表
                updateTrendChart(data) {
                    // 按日期分组统计
                    const dateMap = {};
                    data.forEach(item => {
                        if (dateMap[item.stat_date]) {
                            dateMap[item.stat_date] += item.frequency;
                        } else {
                            dateMap[item.stat_date] = item.frequency;
                        }
                    });
                    
                    const dates = Object.keys(dateMap).sort();
                    const frequencies = dates.map(date => dateMap[date]);
                    
                    const option = {
                        tooltip: {
                            trigger: 'axis'
                        },
                        xAxis: {
                            type: 'category',
                            data: dates
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [
                            {
                                name: '热词频次',
                                type: 'line',
                                smooth: true,
                                data: frequencies,
                                itemStyle: {
                                    color: '#1890ff'
                                }
                            }
                        ]
                    };
                    this.trendChart.setOption(option);
                },

                // 获取模拟数据
                getMockData() {
                    return [
                        { word: '人工智能', frequency: 150, category: '科技', sentiment_score: 0.7, stat_date: '2024-01-15' },
                        { word: 'ChatGPT', frequency: 120, category: '科技', sentiment_score: 0.8, stat_date: '2024-01-15' },
                        { word: '新能源汽车', frequency: 80, category: '汽车', sentiment_score: 0.6, stat_date: '2024-01-15' },
                        { word: '特斯拉', frequency: 60, category: '汽车', sentiment_score: 0.5, stat_date: '2024-01-15' },
                        { word: '裁员', frequency: 100, category: '社会', sentiment_score: -0.6, stat_date: '2024-01-15' },
                        { word: '教育', frequency: 90, category: '教育', sentiment_score: 0.3, stat_date: '2024-01-15' },
                        { word: '医疗', frequency: 70, category: '医疗', sentiment_score: 0.6, stat_date: '2024-01-15' },
                        { word: '疫情', frequency: 50, category: '社会', sentiment_score: -0.2, stat_date: '2024-01-15' },
                        { word: '经济', frequency: 85, category: '经济', sentiment_score: 0.1, stat_date: '2024-01-15' },
                        { word: '房地产', frequency: 65, category: '经济', sentiment_score: -0.3, stat_date: '2024-01-15' }
                    ];
                },

                // 查询数据
                searchData() {
                    this.loadData();
                },

                // 重置筛选条件
                resetFilter() {
                    this.filterParams = {
                        startDate: '',
                        endDate: '',
                        category: ''
                    };
                    layui.use('form', () => {
                        layui.form.val('filterForm', this.filterParams);
                    });
                    this.loadData();
                }
            }
        });

        // 响应式处理
        window.addEventListener('resize', () => {
            const app = document.querySelector('#app').__vue__;
            if (app.hotWordChart) app.hotWordChart.resize();
            if (app.sentimentChart) app.sentimentChart.resize();
            if (app.categoryChart) app.categoryChart.resize();
            if (app.trendChart) app.trendChart.resize();
        });
    </script>
</body>
</html>